(library (commands cd)
  (export cd
          change-directory)
  (import (except (rnrs base) error map)
          (only (guile)
                lambda* λ
                chdir
                simple-format)
          ;; receive form
          (srfi srfi-8)
          (alias)
          (shell-state)
          (commands pwd))


  ;; TODO: use previous result conditionally
  (define cd
    (lambda* (#:optional
              (filename #f)
              #:key
              ;; command interface
              (previous-result '())
              (shell-state default-shell-state)
              (silent #f))
      "Change the current working directory. Use FILENAME, if given,
otherwise use first element of #:PREVIOUS-RESULT."
      (let ([actual-filename
             (if filename
                 filename
                 (car previous-result))])
        ;; (simple-format #t "actual filename: ~a\n" actual-filename)
        (chdir actual-filename)
        (let ([new-pwd (receive (result _) (pwd #:silent #t) (car result))])
          ;; (simple-format #t "new pwd: ~a\n" new-pwd)
          (values (list new-pwd)
                  (update-shell-state shell-state
                                      'current-working-directory
                                      new-pwd))))))


  (alias change-directory cd))
